package cn.kgc.ubagnet.security;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @author shkstart
 * @create 2020-08-06 12:55
 */
@EnableWebSecurity
public class MySecutityConfig extends WebSecurityConfigurerAdapter  {

    @Resource
    UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()//对请求进行授权
                .antMatchers("/css/**",
                        "/fonts/**",
                        "/images/**",
                        "/js/**",
                        "/seleProtype/**",
                        "/seleProduct/**",
                        "/seleProducttext/**"
                       )//使用ANT风格设置要授权的URL地址
                .permitAll()//允许上面使用ANT风格设置的全部请求
                .antMatchers("/")  //开放首页index
                .permitAll()
                .antMatchers("/register")//开放注册页面
                .permitAll()
                .anyRequest()//其他未设置的全部请求
                .authenticated()//需要认证

                .and()
                .formLogin()//设置未授权请求跳转到登录页面
                .loginPage("/login")//指定登录页
                .permitAll()//为登录页设置所有人都可以访问

                 .loginProcessingUrl("/buyer/secutity/do/login.html")//指定登录处理地址，不再使用原来的控制器
                .usernameParameter("phone")//指定页面参数
                .passwordParameter("password")
                .defaultSuccessUrl("/toindex")//登录成功页面
                .failureUrl("/login?error=true")//登录失败跳转URL，并传参方便前端进行判断

                /*.and()
                .logout()//启动退出功能
                .logoutUrl("/admin/security/logout")//指定退出处理地址，不再使用原来的控制器
                .logoutSuccessUrl("/index")
                .and()
                .csrf()
                .disable() // 禁用CSRF功能，如果不禁用，只能发post请求退出，否则报错*/

        ;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {


        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("123456")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip1");
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }


}
